<template>
  <!-- 防止滚动穿透  -->
  <page-meta
    :page-style="
      'overflow:' +
      (showPop['payment'] || showPop['notice'] || showPop['expressDelivery'] ? 'hidden' : 'visible')
    "
  ></page-meta>

  <view v-if="order" class="pageBg">
    <view class="pd262830 box-b">
      <view v-if="disabled" class="mgb20">
        <view class="bgff radius12 pd3032 box-b betweenBox">
          <view class="">
            <view class="lh24 fs24">当前服务进度</view>
            <view class="lh40 fs40 fw500 mgt20" :class="order.colorName">
              {{ order.checkstatusStr }}
            </view>
          </view>
          <view class="flex jsend">
            <c-botton
              v-if="[2].includes(order.checkstatus)"
              name="立即支付"
              class-name="btn-close radius23 pd016 flex-box fs24 minh46 lh26 tac ffmi mgl16 bdff0 sub-color"
              @click="showDrawer('payment', order)"
            ></c-botton>
            <c-botton
              v-if="[0, 1].includes(order.checkstatus)"
              name="录快递"
              @click="showDrawer('expressDelivery', order)"
            ></c-botton>
            <!--            <c-botton-->
            <!--              v-if="[4].includes(order.checkstatus)"-->
            <!--              name="查物流"-->
            <!--              class-name="btn-close radius23 pd016 flex-box fs24 minh46 lh26 tac ffmi mgl16 bd009 theme-color"-->
            <!--              @click="toLogistics(order)">-->
            <!--            </c-botton>-->
          </view>
        </view>
        <view
          v-if="[2, 4].includes(order.checkstatus) && order.fee"
          class="bgff radius12 pd3032 box-b betweenBox mgt20"
        >
          <view class="">
            <view class="lh24 fs24">维修金额</view>
            <view class="lh40 fs40 fw500 mgt20 flex-align sub-color">
              {{ order.fee || 0 }}
              <view class="lh40 fs36 fw500 mgl6">元</view>
            </view>
          </view>
          <view class="flex jsend pdr10">
            <c-botton
              v-if="[2, 4].includes(order.checkstatus)"
              :name="[2].includes(order.checkstatus) ? '未支付' : '已支付'"
              class-name="btn-close radius23 pd016 flex-box fs24 minh46 lh26 tac ffmi mgl16 sub-color"
            ></c-botton>
          </view>
        </view>
        <view v-if="[4].includes(order.checkstatus)" class="bgff radius12 pd3032 box-b mgt20">
          <view class="betweenBox">
            <view class="lh40 fs24 minw108">物流单号</view>
            <view class="lh40 fs32 fw500 ell color1a">
              {{ order.outcomerouterno || '' }}
            </view>
          </view>
          <view class="betweenBox mgt20">
            <view class="lh40 fs24 minw108">快递公司</view>
            <view class="lh40 fs32 fw500 ell color1a">
              {{ order.outcomeroutercrop || '' }}
            </view>
          </view>
        </view>
      </view>

      <view class="bgff radius12 pd4234 box-b">
        <!-- 填报产品 -->
        <view class="flex-align flex1">
          <cInput
            v-if="!disabled"
            bgDefultColor="bdbd00"
            pdClass=""
            v-model="order.serialnumber"
            :requireRed="true"
            :showClear="!disabled"
            :textNameShow="true"
            textName="填报产品"
            placeholder="请输入或扫描产品序列号"
            class="w100"
            :disabled="disabled"
            @blur="blurSerialNumber"
          >
            <template v-if="!disabled && $pallet != 'H5'">
              <view class="mgl10" @click="scanSerialNumber">
                <server-image
                  class="img46 disb"
                  name="repair/20241028005.png"
                  mode="aspectFill"
                ></server-image>
              </view>
            </template>
          </cInput>
          <cInput
            v-else
            bgDefultColor="bdbd00"
            pdClass=""
            v-model="order.confirmserialnumber"
            :requireRed="true"
            :showClear="!disabled"
            :textNameShow="true"
            textName="填报产品"
            placeholder="请输入填报产品"
            class="w100"
            :disabled="disabled"
            @blur="blurSerialNumber"
          ></cInput>
        </view>

        <template v-if="order.productname && order.catelogname">
          <view class="lh36 mgt50 flex-align">
            <view class="color808 minw136 fs28">产品名称：</view>
            <view class="color1a fs28">
              {{ order.productname }}
            </view>
          </view>
          <view class="lh36 mgt20 flex-align">
            <view class="color808 minw136 fs28">产品类别：</view>
            <view class="color1a fs28">
              {{ order.catelogname }}
            </view>
          </view>
        </template>

        <!--   无序列号   -->
        <view v-if="!disabled && guideObj" class="flex1 mgt50">
          <view class="fs24 lh24 mgb20 flex-align color808">
            <view class="flex-align" @click="noSerialNumberChose">
              <view v-if="order.noSerialNumber == '1'" class="">
                <server-image class="img30 mgr10 disb" name="20240702002.png" mode="aspectFill" />
              </view>
              <view v-else class="">
                <server-image
                  class="img30 mgr10 disb"
                  name="repair/20241028010.png"
                  mode="aspectFill"
                ></server-image>
              </view>
              <view class="fs24 lh24 flex-align color808">无序列号</view>
            </view>
            <view class="mgl10 fs24">(找不到序列表或没有序列号时可勾选)</view>
          </view>
          <!--          <view-->
          <!--            class="theme-color fs24 mgt32"-->
          <!--            @click="toWebPage(guideObj)">-->
          <!--            如何找到序列号？-->
          <!--          </view>-->
          <view
            class="theme-color fs24 mgt32 flex-align">
            <view
              @click="guideObj&&guideObj.url && previewImage(guideObj.url)">
              如何找到序列号？
            </view>
          </view>
<!--          <view v-if="guideObj.url" class="mgt18 radius12 ovfh">-->
<!--            <c-image-->
<!--              className="image w625 h400 radius12 ovfh disb"-->
<!--              borderRadius="12rpx"-->
<!--              :src="guideObj.url"-->
<!--              mode="aspectFill"-->
<!--              @click="showBigImg(guideObj.url)"-->
<!--            ></c-image>-->
<!--          </view>-->
        </view>

        <!-- 故障描述 -->
        <view class="flex1 mgt50">
          <cInput
            bgDefultColor="bdbd00"
            pdClass=""
            v-model="order.faulttxt"
            :requireRed="true"
            :showClear="!disabled"
            :textNameShow="true"
            textName="故障描述"
            placeholder="请输入故障描述"
            class="w100"
            :disabled="disabled"
          >
          </cInput>
<!--          <view class="fs24 lh24 mgb20 flex-align color808">-->
<!--            <view v-if="!disabled" class="flex-align lh42 mgr10">-->
<!--              <text class="required red-color">*</text>-->
<!--            </view>-->
<!--            故障描述-->
<!--          </view>-->
<!--          <view class="h168 box-b flex1">-->
<!--            <template v-if="order">-->
<!--              <c-textarea-->
<!--                v-model="order.faulttxt"-->
<!--                class="h168 pdb20 bdbd00 box-b color1a w100 flex1 lh32 fs24 disb"-->
<!--                class-name="color1a w100 flex1 lh32 fs24"-->
<!--                placeholder-class="fs24 colorcc"-->
<!--                :max="1000"-->
<!--                placeholder="请输入故障描述"-->
<!--                :disabled="disabled"-->
<!--              ></c-textarea>-->
<!--            </template>-->
<!--          </view>-->
        </view>

        <!-- 故障照片 -->
        <view
          v-if="(disabled && order.piclist && order.piclist.length > 0) || !disabled"
          class="flex1 mgt50"
        >
          <view class="fs24 lh24 mgb20 flex-align color808">
            <!--            <view v-if="!disabled" class="flex-align lh42 mgr10">-->
            <!--              <text class="required red-color">*</text>-->
            <!--            </view>-->
            故障照片
            <view v-if="disabled" class="mgl10 fs24">(可上传产品图片)</view>
          </view>
          <view class="flex1">
            <c-upload-sec
              v-if="disabled"
              :maxSize="20480"
              :readonly="disabled"
              :showAdd="!disabled"
              :value="order.piclist ? order.piclist : []"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            ></c-upload-sec>
            <c-upload-sec
              v-else
              v-model="order.piclist"
              :maxSize="20480"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            >
              <template slot="add">
                <server-image
                  class="img60 disb"
                  name="add_photo.png"
                  mode="aspectFill"
                ></server-image>
              </template>
            </c-upload-sec>
          </view>
        </view>

        <!-- 产品发票 -->
        <view
          v-if="(disabled && order.invoicelist && order.invoicelist.length > 0) || !disabled"
          class="flex1 mgt50"
        >
          <view class="fs24 lh24 mgb20 flex-align color808">
            <!--            <view v-if="!disabled" class="flex-align lh42 mgr10">-->
            <!--              <text class="required red-color">*</text>-->
            <!--            </view>-->
            产品发票
            <view v-if="disabled" class="mgl10 fs24">(可上传购买订单或发票，以便确认保修期限)</view>
          </view>
          <view class="flex1">
            <c-upload-sec
              v-if="disabled"
              :maxSize="20480"
              :readonly="disabled"
              :showAdd="!disabled"
              :value="order.invoicelist ? order.invoicelist : []"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            ></c-upload-sec>
            <c-upload-sec
              v-else
              v-model="order.invoicelist"
              :maxSize="20480"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            >
              <template slot="add">
                <server-image
                  class="img60 disb"
                  name="add_photo.png"
                  mode="aspectFill"
                ></server-image>
              </template>
            </c-upload-sec>
          </view>
        </view>

        <!-- 异常图片 -->
        <!-- <view
          v-if="(disabled && order.errorlist && order.errorlist.length > 0) || !disabled"
          class="flex1 mgt50"
        > -->
        <view
          v-if="false"
          class="flex1 mgt50"
        >
          <view class="fs24 lh24 mgb20 flex-align color808">
            <!--            <view v-if="!disabled" class="flex-align lh42 mgr10">-->
            <!--              <text class="required red-color">*</text>-->
            <!--            </view>-->
            异常图片
<!--            <view v-if="disabled" class="mgl10 fs24">(可上传异常图片)</view>-->
          </view>
          <view class="flex1">
            <c-upload-sec
              v-if="disabled"
              :maxSize="20480"
              :readonly="disabled"
              :showAdd="!disabled"
              :value="order.errorlist ? order.errorlist : []"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            ></c-upload-sec>
            <c-upload-sec
              v-else
              v-model="order.errorlist"
              :maxSize="20480"
              :max="6"
              :extraData="extraData"
              itemStyles="width: 188rpx;height: 188rpx;margin: 0 10rpx 10rpx;"
              imgClass="ovfh radius12"
              @complete="getPhoto"
            >
              <template slot="add">
                <server-image
                  class="img60 disb"
                  name="add_photo.png"
                  mode="aspectFill"
                ></server-image>
              </template>
            </c-upload-sec>
          </view>
        </view>

      </view>

      <!--   快递信息   -->
      <view v-if="!disabled" class="bgff radius12 pd3032 box-b mgt20">
        <!-- 快递信息 -->
        <view class="flex-align flex1">
          <cInput
            bgDefultColor="bdbd00"
            pdClass=""
            v-model="order.routercode"
            :requireRed="false"
            :showClear="!disabled"
            :textNameShow="true"
            textName="快递信息"
            :textNameTipsShow="true"
            textTipsName="(填写您寄回产品的快递单号)"
            placeholder="请录入快递单号"
            class="w100 mgb40"
            :disabled="disabled"
          >
            <template v-if="!disabled && $pallet != 'H5'">
              <view class="mgl10" @click="scanRouterCode">
                <server-image
                  class="img46 disb"
                  name="repair/20241028005.png"
                  mode="aspectFill"
                ></server-image>
              </view>
            </template>
          </cInput>
        </view>

        <!-- 回寄地址 -->
        <view class="flex1">
          <view class="fs24 lh24 mgb20 flex-align color808">
            <view v-if="!disabled" class="flex-align lh42 mgr10">
              <text class="required red-color">*</text>
            </view>
            回寄地址
            <view v-if="!disabled" class="mgl10 fs24">(填写您的收件信息，以便产品寄回)</view>
          </view>
          <view class="box-b betweenBox flex1 minh74 lh24 bdbd00" @click="toReturnAddress()">
            <view class="flex1 fs24 lh30 pd2500 box-b">
              <view v-if="order.returnAddress" class="color1a zhedie">
                {{ order.returnAddress }}
              </view>
              <view v-else class="fs24">回寄地址</view>
            </view>
            <view>
              <server-image
                class="img1018 disb"
                name="repair/20241028004.png"
                mode="aspectFill"
              ></server-image>
            </view>
          </view>
        </view>

        <!-- 回寄地址 -->
        <!--      <view class="flex-align flex1">-->
        <!--        <cInput-->
        <!--          v-model="order.address"-->
        <!--          bgDefultColor="bdbd00"-->
        <!--          :requireRed="true"-->
        <!--          :showClear="false"-->
        <!--          :textNameShow="true"-->
        <!--          textName="回寄地址"-->
        <!--          :textNameTipsShow="true"-->
        <!--          textTipsName="(填写您的收件信息，以便产品寄回)"-->
        <!--          placeholder="请选择回寄地址"-->
        <!--          class="w100"-->
        <!--          bgDefultColor="bdbe7 zIndex10"-->
        <!--          pdClass=""-->
        <!--          :disabled="true"-->
        <!--          :clickable="true"-->
        <!--          @toPage="toPage('/pages/addressManage/editAddress/editAddress',true)"-->
        <!--        >-->
        <!--          <template-->
        <!--            v-if="!disabled">-->
        <!--            <view>-->
        <!--              <server-image-->
        <!--                class="img40 disb"-->
        <!--                name="20230824002.png"-->
        <!--                mode="aspectFill">-->
        <!--              </server-image>-->
        <!--            </view>-->
        <!--          </template>-->
        <!--        </cInput>-->
        <!--      </view>-->

      </view>

      <!--   服务中心邮寄地址在客户提交维修诉求单中展示出来     -->
      <view
        v-if="addressinfo"
        class="bgff radius12 pd3032 box-b mgt20">
        <view class="betweenBox minh60">
          <view class="lh42 fs28 color808 flex-align">
            寄修地址:
          </view>
          <view class="flex-box minw150 h60 pd020 box-b radius10 fs26 mgl10"
                :class="[againClick ? 'bg00901 theme-color' : 'bgd2 white']"
                @tap="againClick&&copyAddress()">
            复制
          </view>
        </view>
        <view class="lh36 fs28 mgt36 flex-align">
          <view class="color808 minw136 fs28">
            联系人:
          </view>
          <view class="color1a fs28">
            {{addressinfo.name || ''}}
          </view>
        </view>
        <view class="lh36 fs28 mgt20 flex-align">
          <view class="color808 minw136 fs28">
            联系电话:
          </view>
          <view class="color1a fs28">
            {{addressinfo.mob || ''}}
          </view>
        </view>
        <view class="lh36 fs28 mgt20 flex-start">
          <view class="color808 minw136 fs28">
            寄件地址:
          </view>
          <view class="color1a fs28">
            {{addressinfo.address || ''}}
          </view>
        </view>
      </view>

      <!--   手机号未授权   -->
      <button
        v-if="memberInfo && memberInfo.hasmob == 0"
        class="w570 h90 flex-box background-theme white radius45 fw400 fs34 ffmi ltsp8 mg55a20"
        :class="{ 'bgd2': submitDisabled }"
        :open-type="!submitDisabled ? 'getPhoneNumber' : ''"
        @getphonenumber="!submitDisabled && getPhoneNumber($event)"
      >
        提交
      </button>
      <view
        v-else
        class="w570 h90 flex-box background-theme white radius45 fw400 fs34 ffmi ltsp8 mg55a20"
        :class="{ 'bgd2': submitDisabled }"
        @click="!submitDisabled && submit()"
      >
        {{ disabled ? '返回' : '提交' }}
      </view>
    </view>

    <!--  支付维修费用  -->
    <tips-popup
      topTitle="支付维修费用"
      topClass="mg48440 pdb38 box-b bdb808 flex-align lh34 fs34 fw600 ffmi color26"
      classNameMask="bg00006"
      :show="showPop['payment']"
      type="bottom-radio"
      :showThemeDelete="true"
      class="middle-box box-b"
      style="position: relative"
      @hide="closeDrawer('payment')"
    >
      <view v-if="order" class="box-b mg044">
        <text-item
          className="fs26 color26 lh28 mgt44 mgb16"
          title="本次售后服务待支付费用"
        ></text-item>
        <view class="mgt100 flex-box color26 ffpo">
          <view class="fs102">
            {{ (order.fee || 0) + '' }}
          </view>
          <view class="fs36 mgt33 mgl10">元</view>
        </view>
        <view
          class="w570 h90 flex-box background-sub white radius45 fw400 fs34 ffmi ltsp8 mg95a50"
          :class="{ 'bgd2': !againClick }"
          @click="againClick && api_func_getpayparams()"
        >
          立即支付
        </view>
      </view>
    </tips-popup>

    <!--  报修须知  -->
    <tips-popup
      topTitle="报修须知"
      topClass="mg48440 pdb38 box-b bdb808 flex-box lh34 fs34 fw600 ffmi color26"
      classNameMask="bg00006"
      :show="showPop['notice']"
      type="middle"
      :showThemeDelete="true"
      class="middle-box box-b"
      style="position: relative"
      @hide="notAgreeNow()"
    >
      <view class="box-b mg044">
        <scroll-view class="box-b ovfya minh120 maxh600 mgt30 mgb30" :scroll-y="true">
          <view v-if="guideObj && guideObj.repairnotice" class="lh32 fs24 color26">
            <c-rich-text :content="guideObj.repairnotice"></c-rich-text>
          </view>
        </scroll-view>
        <view class="bdt808">
          <view class="flex-align mgt20">
            <view class="flex-align" @click="agree = !agree">
              <view v-if="agree" class="">
                <server-image
                  class="img30 mgr10 disb"
                  name="repair/20241031004.png"
                  mode="aspectFill"
                />
              </view>
              <view v-else class="">
                <server-image
                  class="img30 mgr10 disb"
                  name="repair/20241031003.png"
                  mode="aspectFill"
                ></server-image>
              </view>
              <view class="lh32 fs24 color26 mgl6">我已阅读并同意《报修须知》的内容</view>
            </view>
          </view>
          <view
            class="w300 h74 flex-box background-sub white radius38 fw400 fs34 ffmi mg30a"
            :class="{ 'bgd2': !againClick || countDown > 0 }"
            @click="againClick && countDown <= 0 && agreeNow()"
          >
            <view class="flex-box ltsp8">同意</view>
            <view v-if="countDown" class="flex-box">({{ countDown }}S)</view>
          </view>
        </view>
      </view>
    </tips-popup>

    <!--  录入快递  -->
    <tips-popup
      topTitle="快递信息录入"
      topClass="mg48440 pdb38 box-b bdb808 flex-align lh34 fs34 fw600 ffmi color26"
      classNameMask="bg00006"
      :show="showPop['expressDelivery']"
      type="bottom-radio"
      :showThemeDelete="true"
      class="middle-box box-b"
      style="position: relative"
      @hide="closeDrawer('expressDelivery')"
    >
      <view class="box-b mg044">
<!--        <text-item-->
<!--          className="fs26 color26 lh28 mgt44 mgb16"-->
<!--          title="请录入快递信息，以便我们收到包裹第一时间为您服务"-->
<!--        ></text-item>-->
<!--        <template v-if="showPop['expressDelivery']">-->
<!--          <c-textarea-->
<!--            v-model="order.routercode"-->
<!--            class="h142 pd1820 bdd00 radius12 box-b color1a w100 flex1 lh32 fs24 disb"-->
<!--            class-name="color1a w100 flex1 lh32 fs24"-->
<!--            placeholder-class="fs24 colorb3"-->
<!--            :max="500"-->
<!--            placeholder="请录入快递单号"-->
<!--          ></c-textarea>-->
<!--        </template>-->
        <cInput
          bgDefultColor="bdbd00"
          pdClass=""
          v-model="order.routercode"
          :requireRed="true"
          :showClear="true"
          textClass="fs26 color26 lh28 mgt44 mgb16 flex-align"
          :textNameShow="true"
          textName="请录入快递信息，以便我们收到包裹第一时间为您服务"
          placeholder="请录入快递单号"
          class="w100 mgb40"
        >
          <template v-if="$pallet != 'H5'">
            <view class="mgl10" @click="scanRouterCode">
              <server-image
                class="img46 disb"
                name="repair/20241028005.png"
                mode="aspectFill"
              ></server-image>
            </view>
          </template>
        </cInput>
        <view
          class="w570 h90 flex-box background-sub white radius45 fw400 fs34 ffmi ltsp8 mg55a50"
          :class="{ 'bgd2': btnDisabled }"
          @click="!btnDisabled && api_func_submitRouterInfo()"
        >
          保 存
        </view>
      </view>
    </tips-popup>

    <!--  图片大图  -->
    <c-image-preview v-if="bigImg" :src="bigImg" :scaleShow="true" @click="bigImg = ''"></c-image-preview>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import cInput from '@/components/c-input';
import cTextarea from '@/components/c-textarea';
import cUploadSec from '@/components/c-upload-sec';
import tipsPopup from '@/components/tips-popup';
// 图片大图
import cImagePreview from '@/components/c-image-preview';
// 复制地址
import { uniSetClipboardData } from '@/common/utils';
export default {
  name: 'repair-report-detail',
  components: {
    cInput,
    cTextarea,
    cUploadSec,
    tipsPopup,
    // 图片大图
    cImagePreview,
  },
  data() {
    return {
      orderid: '',
      checkstatus: '',
      order: {},
      showOrder: false,
      title: '产品报修',
      // 图片
      extraData: {
        fileDir: 'file',
      },
      disabled: false,
      allowRequest: true,
      guideObj: {
        url: '',
        repairnotice: '',
      },
      againClick: true, //禁止数据频繁切换
      // 弹框
      showPop: {
        expressDelivery: false, // 录快递
        payment: false, // 支付
        notice: false, // 报修须知
      },
      countDown: 5,
      timer: null,
      agree: false,
      // 图片大图
      bigImg: '',
      // 服务中心邮寄地址在客户提交维修诉求单中展示出来
      addressinfo: {},

    };
  },
  computed: {
    ...mapState({
      memberInfo: (state) => state.memberInfo || {},
    }),
    btnDisabled: function () {
      let vm = this;
      return !vm.order.routercode;
    },
    submitDisabled: function () {
      let vm = this;
      if (!vm.disabled) {
        if (vm.order) {
          return (
            !(vm.order.serialnumber || vm.order.noSerialNumber) ||
            !vm.order.faulttxt ||
            !vm.order.address ||
            !vm.allowRequest
            // || vm.order.piclist.length==0
            // || vm.order.invoicelist.length==0
            // || vm.order.errorlist.length==0
          );
        }
      } else {
        return false;
      }
    },
  },
  onLoad(e) {
    if (e && e.orderid) {
      // this.order.orderid = e.orderid;
      if (e && e.checkstatus) {
        this.checkstatus = Number(e.checkstatus);
      }
      // checkstatus!=0不可编辑
      if (![0].includes(this.checkstatus)) {
        this.disabled = true;
      } else {
        this.disabled = false;
      }
      this.getList(false, e.orderid);
    } else {
      this.disabled = false;
      this.api_ui_getguidepic();

      // 填报页面填写的内容缓存到本地，提交之后清空缓存
      if ([''].includes(this.checkstatus)) {
        const repairReportDetail = uni.getStorageSync('repairReportDetail');
        if(repairReportDetail){
          this.order = {
            ...this.order,
            ...JSON.parse(repairReportDetail)
          }
        }
      }

    }

    // 服务中心邮寄地址在客户提交维修诉求单中展示出来
    this.api_ui_getrecvaddress();
  },
  onShow() {
    const vm = this;
    vm.clearStorageSync();
  },
  onPullDownRefresh() {
    const vm = this;
    vm.initListDate();
    if (vm.order.orderid) {
      vm.getList().then(() => {
        uni.stopPullDownRefresh();
      });
    } else {
      vm.disabled = false;
      vm.api_ui_getguidepic().then(() => {
        uni.stopPullDownRefresh();
      });
    }
  },
  destroyed() {
    const vm = this;
    vm.clearStorageSync();
    vm.clearTime();

    // 填报页面填写的内容缓存到本地，提交之后清空缓存
    console.log('vm.checkstatus',vm.checkstatus)
    if ([''].includes(vm.checkstatus)) {
      uni.setStorageSync('repairReportDetail', JSON.stringify(vm.order));
    }

  },
  methods: {
    toReturnAddress() {
      const vm = this;
      let addressObj = {};
      if (vm.order && vm.order.address) {
        addressObj = {
          recvname: vm.order.recvname,
          mob: vm.order.mob,
          zone: vm.order.zone,
          address: vm.order.address,
          city: vm.order.city,
          district: vm.order.district,
          province: vm.order.province,
          defaultIndexs: vm.order.defaultIndexs,
        };
      }
      if (!vm.isObjectEmptyOrUndefined(addressObj)) {
        vm.toPage(
          '/pages/addressManage/editAddress/editAddress?addressObj=' + JSON.stringify(vm.order),
          true
        );
        return;
      }
      vm.toPage('/pages/addressManage/editAddress/editAddress', true);
    },
    clearStorageSync() {
      const vm = this;
      let repairReportAddress = uni.getStorageSync('repairReportAddress');
      if (repairReportAddress) {
        repairReportAddress = JSON.parse(repairReportAddress);
        vm.order = {
          ...vm.order,
          ...repairReportAddress,
        };
        uni.removeStorageSync('repairReportAddress');
      }

      // 报修订单详情改变
      const repairChangeDetail = uni.getStorageSync('repairChangeDetail');
      if (repairChangeDetail) {
        vm.disabled = true;
        vm.order.orderid = repairChangeDetail;
        vm.getList();
        uni.removeStorageSync('repairChangeDetail');
      }
    },
    initListDate() {
      const vm = this;
      if (!vm.order && vm.order.orderid) vm.order = {};
      vm.showOrder = false;
      vm.countDown = 5;
      vm.clearTime();
      vm.agree = false;
      vm.showPop = {
        expressDelivery: false, // 录快递
        payment: false, // 支付
        notice: false, // 报修须知
      };
    },
    getList(againClick = false, orderid = '') {
      const vm = this;
      uni.showLoading({
        title: 'loading...',
      });

      let param = {
        orderid: orderid ? orderid : vm.order.orderid,
        openid: vm.memberInfo.openid,
      };
      if (againClick) {
        if (!vm.againClick)
          return new Promise(function (resolve) {
            resolve();
          });
        vm.againClick = false;
      }
      return new Promise(function (resolve) {
        vm.apiUrl
          .api_func_getrepairorderdetail({
            data: param,
          })
          .then(async (res) => {
            const { code, data } = res.data;
            if (code == 0 && data) {
              // 下单时间
              data.submittime = data.submittime
                ? vm.dateFormatFun(data.submittime, 'YYYY-MM-DD hh:mm:ss')
                : '';
              // 物流进度时间
              if (data.logisticsList && data.logisticsList.length > 0) {
                data.logisticsList = data.logisticsList.map((item) => {
                  return {
                    ...item,
                    time: item.time ? vm.dateFormatFun(item.time, 'YYYY-MM-DD') : '',
                  };
                });
              }
              // 填报产品
              let faulttxt = await vm.filterSpecialSymbol(data.faulttxt);
              data.faulttxt = data.faulttxt ? faulttxt : '';
              let checkstatusObj = {
                0: {
                  checkstatusStr: '待受理',
                  className: 'bg61601',
                  colorName: 'color616',
                },
                1: {
                  checkstatusStr: '已受理',
                  className: 'bg00901',
                  colorName: 'theme-color',
                },
                2: {
                  checkstatusStr: '待支付',
                  className: 'bgff001',
                  colorName: 'colorff0',
                },
                3: {
                  checkstatusStr: '维修中',
                  className: 'bgff901',
                  colorName: 'colorff9',
                },
                4: {
                  checkstatusStr: '归还中',
                  className: 'bg61601',
                  colorName: 'color616',
                },
                5: {
                  checkstatusStr: '已签收',
                  className: 'bg36b01',
                  colorName: 'color36b',
                },
                6: {
                  checkstatusStr: '已完成',
                  className: 'bg36b01',
                  colorName: 'color36b',
                },
                7: {
                  checkstatusStr: '已取消',
                  className: 'bg80801',
                  colorName: 'color808',
                },
                8: {
                  checkstatusStr: '已关闭',
                  className: 'bg80801',
                  colorName: 'color808',
                },
              };
              if (data) {
                for (let path in checkstatusObj) {
                  if (data.checkstatus == path) {
                    data.checkstatusStr = checkstatusObj[path].checkstatusStr;
                    data.className = checkstatusObj[path].className;
                    data.colorName = checkstatusObj[path].colorName;
                    break;
                  } else {
                    data.className = checkstatusObj[8].className;
                    data.colorName = checkstatusObj[8].colorName;
                  }
                }
              }

              vm.order = {
                ...data,
                returnAddress: [
                  data.recvname,
                  data.mob,
                  data.province + data.city + data.district + data.address,
                ].join(','),
                noSerialNumber: data.serialNumber == '' ? '' : '1',
              };

              if ([0].includes(vm.order.checkstatus)) {
                vm.api_ui_getguidepic(true);
              }
            }
          });
        resolve();
      }).finally(() => {
        if (againClick) {
          vm.againClick = true;
        }
        uni.hideLoading();
      });
    },
    toLogistics(order) {
      const vm = this;
      uni.setStorageSync(`order_${order.orderid}`, JSON.stringify(order));
      vm.toPage('/pages/packages/member/logistics/logistics?orderid=' + order.orderid, true);
    },
    // 图片
    getPhoto(e) {},
    async submit(code) {
      let vm = this;

      if (vm.disabled) {
        vm.goBack();
        return;
      }

      if (!vm.isValidPhoneNumber(vm.order.mob)) {
        vm.showMessage({
          title: '请输入正确格式的手机号码',
          // icon: 'error',
          duration: 1500,
        });
        return;
      }

      // 正则表达式，用于判断字符串是否不包含汉字
      if (vm.containsChinese(vm.order.routercode)) {
        vm.showMessage({
          title: '快递单号不可包含中文',
          duration: 1500,
        });
        return;
      }

      if (!vm.allowRequest) return;
      if (!vm.memberInfo.openid || vm.memberInfo.hasmob == 0) {
        // #ifdef MP-WEIXIN
        // 新增报修，需要获取用户手机号，若没有则调用微信获取授权
        await vm.$store.dispatch('check_wx_login', {
          isSubmit: true,
          code: code ? code : '',
        });
        // #endif
        vm.showMessage({
          title: '提交失败: H5暂不可用，请移步小程序端使用',
          // icon: 'error',
          duration: 1500,
        });
        if (!vm.memberInfo.openid || vm.memberInfo.hasmob == 0) return;
      }
      let data = {
        openid: vm.memberInfo.openid,
        txt: vm.order.faulttxt,
        // serialnumber: vm.order.serialnumber,
        piclist: vm.order.piclist,
        invoicelist: vm.order.invoicelist,
        errorlist: vm.order.errorlist,
        recvname: vm.order.recvname,
        mob: vm.order.mob,
        province: vm.order.province,
        city: vm.order.city,
        district: vm.order.district,
        address: vm.order.address,
        defaultIndexs: vm.order.defaultIndexs,
        // address: vm.order.address,
        routercode: vm.order.routercode,
        noSerialNumber: vm.order.noSerialNumber,
      };
      if (vm.order.orderid) {
        data.orderid = vm.order.orderid;
      }
      if (vm.order.serialnumber) {
        // 序列号提交时转大写
        data.serialnumber = vm.order.serialnumber.toUpperCase();
      }
      // console.log("data",data)
      // return

      vm.allowRequest = false;
      uni.showLoading({
        title: '加载中...',
      });
      vm.apiUrl
        .api_func_submitrepairorder({
          data: data,
        })
        .then((res) => {
          const {
            code,
            msg: message = '',
            data: { orderid = '', addressinfo = {} },
          } = res.data;
          // console.log("res",res)
          uni.hideLoading();
          if (code == 0) {
            uni.setStorageSync('repairChange', true);
            uni.setStorageSync('repairChangeDetail', orderid);

            // 填报页面填写的内容缓存到本地，提交之后清空缓存
            if ([''].includes(vm.checkstatus)) {
              uni.removeStorageSync('repairReportDetail');
            }

            vm.allowRequest = true;
            vm.redirectToPage(
              '/pages/order/pay-success/pay-success?orderid=' +
              orderid +
              '&type=' +
              2 +
              '&title=提报成功' +
              '&addressinfo=' +
              JSON.stringify(addressinfo),
              true
            );
          } else {
            uni.showModal({
              title: '提示',
              content: message || '提交失败',
              showCancel: false,
              confirmText: '确定',
              success: () => {},
            });
            vm.allowRequest = true;
          }
        });
    },
    notAgreeNow() {
      const vm = this;
      vm.sleep(50).then(() => {
        vm.closeDrawer('notice');
        vm.goBack();
      });
    },
    agreeNow() {
      const vm = this;
      if (!vm.agree) {
        if (!vm.againClick) return;
        vm.againClick = false;
        vm.showMessage({
          title: '请勾选我已阅读并同意《报修须知》的内容',
          duration: 2000,
        });
        vm.sleep(2000).then(() => {
          vm.againClick = true;
        });
        return;
      }
      vm.sleep(300).then(() => {
        vm.closeDrawer('notice');
      });
    },
    clearTime() {
      const vm = this;
      if (vm.timer) {
        clearInterval(vm.timer);
      }
    },
    api_ui_getguidepic(notShowNotice = false) {
      const vm = this;

      uni.showLoading({
        title: '加载中...',
      });
      return new Promise(function (resolve) {
        vm.apiUrl.api_ui_getguidepic().then(async (res) => {
          uni.hideLoading();
          const { code, data } = res.data;
          if (code == 0) {
            let repairnotice = await vm.filterSpecialSymbol(data.repairnotice);
            vm.guideObj = {
              ...data,
              repairnotice: repairnotice ? repairnotice : '',
            };
            if (!notShowNotice) {
              let memberAddress = uni.getStorageSync('memberAddress');
              if (memberAddress) {
                memberAddress = JSON.parse(memberAddress);
                vm.order = {
                  ...vm.order,
                  ...memberAddress,
                };
              }
              vm.showDrawer('notice');
              vm.clearTime();
              vm.timer = setInterval(() => {
                if (vm.countDown > 0) {
                  vm.countDown -= 1;
                }
                if (vm.countDown <= 0) {
                  vm.clearTime();
                }
              }, 1000);
            }
          }
          resolve();
        });
      });
    },
    toWebPage() {
      const vm = this;
      if (vm.guideObj && vm.guideObj.repairnotice) {
        uni.setStorageSync('swiperContent', vm.guideObj.repairnotice);
        vm.toPage(
          '/pages/index/webPage/webPage?richText=' +
            vm.guideObj.repairnotice +
            '&title=如何找到序列号？',
          true
        );
      } else {
        vm.showMessage({
          title: '指引失败: 富文本为空',
          icon: 'error',
          duration: 1500,
        });
      }
    },
    blurSerialNumber() {
      const vm = this;
      if (vm.order.serialnumber) {
        vm.api_func_checkserialnumber(vm.order.serialnumber).then((data) => {
          if (data) {
            vm.order = {
              ...vm.order,
              serialnumber: vm.order.serialnumber,
              productname: data.name || '',
              catelogname: data.catename || '',
            };
          } else {
            vm.order = {
              ...vm.order,
              serialnumber: '',
              productname: '',
              catelogname: '',
            };
          }
        });
      } else {
        vm.order = {
          ...vm.order,
          serialnumber: '',
          productname: '',
          catelogname: '',
        };
      }
    },
    scanSerialNumber() {
      const vm = this;
      // 调用扫码API
      uni.scanCode({
        success: (res) => {
          // 扫码成功回调
          console.log('扫码结果: ' + res.result);
          console.log('条形码类型: ' + res.scanType);
          // 这里可以执行进一步的处理，例如验证序列号等
          // 根据res.result中的内容进行处理
          vm.order = {
            ...vm.order,
            serialnumber: res.result,
          };
          vm.blurSerialNumber(vm.order.serialnumber);
        },
        fail: (err) => {
          // 扫码失败回调
          console.error('扫码失败: ', err);
          const { errMsg } = err;
          if (errMsg) {
            vm.showMessage({
              title: errMsg || 'scanCode API 失效',
              icon: 'error',
              duration: 1500,
            });
          }
        },
      });
    },
    // 快递信息扫码录入
    scanRouterCode() {
      const vm = this;
      // 调用扫码API
      uni.scanCode({
        success: (res) => {
          // 扫码成功回调
          console.log('扫码结果: ' + res.result);
          console.log('条形码类型: ' + res.scanType);
          // 这里可以执行进一步的处理，例如验证序列号等
          // 根据res.result中的内容进行处理
          vm.order = {
            ...vm.order,
            routercode: res.result,
          };
        },
        fail: (err) => {
          // 扫码失败回调
          console.error('扫码失败: ', err);
          const { errMsg } = err;
          if (errMsg) {
            vm.showMessage({
              title: errMsg || 'scanCode API 失效',
              icon: 'error',
              duration: 1500,
            });
          }
        },
      });
    },
    api_func_checkserialnumber(serialnumber) {
      const vm = this;
      uni.showLoading({
        // title: '加载中...'
        title: '序列号验证中...',
      });
      return new Promise((resolve) => {
        vm.apiUrl
          .api_func_checkserialnumber({
            data: {
              code: serialnumber,
            },
          })
          .then((res) => {
            uni.hideLoading();
            const { code, msg: message = '', data } = res.data;

            if (code == 0) {
              if (data) {
                resolve(data);
              }
            } else {
              vm.showMessage({
                title: message || '序列号错误',
                icon: 'error',
                duration: 1500,
              });
              resolve();
            }
          });
      });
    },
    noSerialNumberChose() {
      const vm = this;
      if (!vm.order.noSerialNumber) {
        vm.order = {
          ...vm.order,
          serialnumber: '',
          noSerialNumber: 1,
        };
      } else {
        vm.order = {
          ...vm.order,
          noSerialNumber: '',
        };
      }
    },
    // 弹框
    showDrawer(name, order = false) {
      this.showPop[name] = true;
      if (order) {
        this.order = order;
      }
    },
    closeDrawer(name) {
      this.showPop[name] = false;
    },
    // 录入快递单号
    api_func_submitRouterInfo() {
      const vm = this;
      // 正则表达式，用于判断字符串是否不包含汉字
      if (vm.containsChinese(vm.order.routercode)) {
        vm.showMessage({
          title: '快递单号不可包含中文',
          duration: 1500,
        });
        return;
      }
      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...',
      });
      vm.apiUrl
        .api_func_submitRouterInfo({
          data: {
            orderid: vm.order.orderid,
            routercode: vm.order.routercode,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code, msg: message = '' } = res.data;
          if (code == 0) {
            vm.closeDrawer('expressDelivery');
            vm.showMessage({
              title: '录入快递单号成功',
              duration: 2000,
            });
            vm.sleep(2000).then(() => {
              uni.setStorageSync('repairChange', true);
              uni.setStorageSync('repairChangeDetail', vm.order.orderid);
              // vm.goBack()
              vm.getList();
            });
          } else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500,
            });
          }
        })
        .finally(() => {
          vm.sleep(1500).then(() => {
            vm.againClick = true;
          });
        });
    },
    // 图片大图
    showBigImg(img) {
      this.bigImg = img;
    },
    getPhoneNumber(e) {
      const vm = this;
      console.log(e.detail.code); // 动态令牌
      console.log(e.detail.errMsg); // 回调信息（成功失败都会返回）
      console.log(e.detail.errno); // 错误码（失败时返回）
      if (e.detail.code) {
        vm.submit(e.detail.code);
      }
    },
    // 微信支付 start
    // 支付成功
    paySuccess(orderid, againClick = false) {
      const vm = this;
      vm.api_func_getrepairorderdetail().then(() => {
        if (vm.order.paystatus == 1) {
          vm.toPage(
            '/pages/order/pay-success/pay-success?orderid=' +
              (vm.order && vm.order.orderid ? vm.order.orderid : orderid) +
              '&fromPage=reportDetail',
            true
          );
          // uni.redirectTo({
          //   url: `/pages/order/pay-success/pay-success?orderid=${orderid}`,
          // });
        } else {
          // if (!againClick) {
          //   vm.showPop['confirmResults'] = true;
          // } else {
          //   vm.showPop['pendding'] = true;
          // }
        }
      });
    },
    api_func_getrepairorderdetail() {
      const vm = this;
      uni.showLoading({
        title: '加载中...',
      });
      return new Promise((resolve) => {
        vm.apiUrl
          .api_func_getrepairorderdetail({
            data: {
              orderid: vm.order.orderid,
              openid: vm.memberInfo.openid,
            },
          })
          .then((res) => {
            uni.hideLoading();
            const { code, data } = res.data;
            if (code == 0) {
              if (data) {
                vm.order = {
                  ...vm.order,
                  ...data,
                };
                resolve();
              }
            }
          });
      });
    },
    api_func_getpayparams() {
      const vm = this;

      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...',
      });
      vm.apiUrl
        .api_func_getpayparams({
          data: {
            orderid: vm.order.orderid,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code, msg: message = '', data } = res.data;
          if (code == 0) {
            // 调起微信支付
            uni.requestPayment({
              provider: 'wxpay', // 支付服务提供商，如 'wxpay'、'alipay'
              // 由支付服务提供商返回的支付信息
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {
                console.log('支付成功', res);
                vm.closeDrawer('payment');
                vm.showMessage({
                  title: '支付成功',
                  duration: 2000,
                }).then(() => {
                  uni.setStorageSync('repairChange', true);
                  uni.setStorageSync('repairChangeDetail', vm.order.orderid);
                  vm.paySuccess(vm.order.orderid);
                });
              },
              fail: function (err) {
                console.log('支付失败', err);
                const { errMsg = '' } = err;
                vm.showMessage({
                  title: errMsg || '支付失败',
                  // icon: 'error',
                  duration: 1500,
                });
              },
              complete: function () {
                console.log('支付流程完成');
              },
            });
          } else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500,
            });
          }
        })
        .finally(() => {
          vm.sleep(1500).then(() => {
            vm.againClick = true;
          });
        });
    },
    // 微信支付 end
    // 服务中心邮寄地址在客户提交维修诉求单中展示出来
    copyAddress(){
      const vm = this;
      const { name, mob, address } = this.addressinfo;
      let formattedAddress = `${'联系人：'+name}\n${'联系电话：'+mob}\n${'联系地址：'+address}`;
      vm.againClick = false
      // 获取剪贴板的内容
      uniSetClipboardData({
        data: formattedAddress,
        success: (res) => {
          console.log('res',res)
          const { errMsg } = res;
          if (errMsg == 'setClipboardData:ok'){
            // 覆盖
            uni.showToast({
              title:"复制成功"
            })
          } else {
            // 覆盖
            uni.showToast({
              title:"复制成功"
            })
          }
        },
        fail: function (err) {
          console.log(err);
          const { errMsg } = err;
          if(errMsg) {
            vm.showMessage({
              title: errMsg || 'setClipboardData API 失效',
              // icon: 'error',
              duration: 1500,
            });
          }
        },
      });

      vm.sleep(1500).then(() => {
        vm.againClick = true;
      });
    },
    api_ui_getrecvaddress() {
      const vm = this;
      uni.showLoading({
        title: '加载中...'
      })
      vm.apiUrl
        .api_ui_getrecvaddress()
        .then((res) => {
          uni.hideLoading();
          const { code,msg:message='', data } = res.data;
          if(code == 0){
            vm.addressinfo = data;
          }else {
            // vm.showMessage({
            //   title: message,
            //   icon: 'error',
            //   duration: 1500
            // })
          }
        })
    },

  },
};
</script>

<style lang="less" scoped></style>
